<template>
  <div @click="showDialog">
    <slot/>
    <el-dialog v-model="loginDialogVisible" appendToBody title="" width="2.6rem">
      <div class="padding-30-40">
        <h2 class="margin-0">登录</h2>
        <el-form label-width="80px" ref="formRef" :model="formData.form" :rules="rules">
          <el-form-item label="用户名" required prop="userName" class="margin-30-0">
            <el-input v-model="formData.form.userName" placeholder="请输入用户名">
              <template #prefix>
                <svg-icon icon="user-bold" width="22px" height="22px" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="密码" required prop="password">
            <el-input type="password" v-model="formData.form.password" placeholder="请输入密码">
              <template #prefix>
                <svg-icon icon="lock" width="22px" height="22px" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item v-show="this.current_menu === 'register'" label="确认密码" prop="password">
            <el-input type="password" v-model="confirmPwd"></el-input>
          </el-form-item>
          <ForgetPwdDialog>
            <el-link :underline="false" class="right color-blue-light hover" @click="loginDialogVisible = false">忘记密码？</el-link>
          </ForgetPwdDialog>
        </el-form>
      </div>
      <template #footer>
        <div class="margin-40">
          <el-button @click="submit(formData.form)" :loading="loading" type="primary" class="full">
            {{ this.current_menu === "login" ? "登录" : "注册" }}
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts">

import {Options} from "vue-class-component";
import BasePage from "../pages/BasePage";
import {useRoute, useRouter} from "vue-router";
import {reactive, ref} from "vue";
import {loginAPI, registerAPI} from "../request/api";
import {ElMessage} from "element-plus";
import {storeToRefs} from "pinia";
import {useUser} from "@/store/user";
import ForgetPwdDialog from "@/components/ForgetPwdDialog.vue";

@Options({
  name: 'LoginDialog',
  components: { ForgetPwdDialog }
})
export default class LoginDialog extends BasePage {
  router = useRouter()
  route = useRoute()

  loginDialogVisible = false
  //登录相关
  // user = useUser(); // 相当于setup方法
  // user = JSON.parse(sessionStorage.getItem('userInfo')) ? JSON.parse(sessionStorage.getItem('userInfo')) : {}
  useUser = useUser()
  user = storeToRefs(useUser())?.userInfo

  confirmPwd = ''

  formData = reactive({
    form: {
      userName: '',
      password: ''
    },
    tab_menu:
        [
          {type: "login", label: "登录"},
          {type: "register", label: "注册"},
        ]
  })

  toggleMenu(type) {
    this.current_menu = type;
  };

  current_menu = this.formData.tab_menu[0].type;

  // 获取页面组件对象
  formRef = ref();
  rules = {
    username: [
      {required: true, message: '必须输入用户名', trigger: 'blur'},
    ],
    password: [
      {required: true, message: '必须输入密码', trigger: 'blur'},
    ]
  }

  // 传递参数的方式
  async submit(form) {
    try {
      this.loading = true
      if (this.current_menu === 'register') {
        if (form.password === this.confirmPwd) {
          let res = await registerAPI(form);
          if (res.code === '000') {
            ElMessage.error(res.message)
            this.goPage('/')
          } else {
            ElMessage.error(res.errMessage)
          }
        } else {
          ElMessage.error('密码不一致')
        }
      } else {
        await this.formRef.validate()
        let res = await loginAPI(form);
        if (res.code === '000') {
          var userInfo = res.data.userInfo;
          this.user = userInfo;
          window.sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
          this.useUser.reloadFromSession()
          this.loginDialogVisible = false
          this.goPage('/')
          ElMessage.success('登录成功，欢迎！')
        } else {
          ElMessage.error(res.errMessage)
        }
      }
    } catch (err) {
      console.log(err)
    }
    this.loading = false
  }

  //注销登录信息
  loginOut = () => {
    window.sessionStorage.clear();
    this.user = {}
  };

  //首页前端栏

  goPage(path: string) {
    this.$router.push({path})
  }

  showDialog() {
    this.loginDialogVisible = true
  }

}
</script>

<style lang="scss" scoped>
.el-input, .el-button {
  height: 48px;
}
:deep(.el-form-item__label) {
  display: none;
}
</style>